<template>
	<view v-if="labelData.name" :style="{'display':'inline-block','padding':'5px 10px','border-radius':'5px',
		'background-color':labelData.cssClass,'color':labelData.cssStyle
		}">
		{{labelData.name}}
	</view>
</template>
<script>
/**
 * @property {Object} value 用于取字典的值
 * @property {String} dictType 字典类型，从字典里获取
 * <dictLabel :value="value" dict-type="U8_SU_TH_ROW_STATUS">
 */
import dictManager from '@/common/dictManager.js';

// 全局请求计数器（用于调试）
let requestCounter = 0;

export default {
	props: {
		value: {
			type: String,
			default: ''
		},
		dictType: {
			type: String,
			default: ''
		},
	},
	data() {
		return {
			labelData:{
			},
			isLoading: false, // 防止重复请求
			loadDataTimer: null, // 防抖定时器
			cleanupTimer: null, // 清理缓存定时器
		};
	},
	watch: {
		value: {
			handler(val, oldVal) {
				console.log(val, oldVal,'value');
				// 防抖处理，避免频繁调用
				this.debouncedLoadData();
			},
			deep: true,
			immediate: true
		},
		dictType: {
			handler(val, oldVal) {
				console.log(val, oldVal, 'dictType');
				// 防抖处理，避免频繁调用
				this.debouncedLoadData();
			},
			deep: true,
			immediate: true
		}
	},
	onLoad(){
		console.log('onLoad');
	},
	onReady(){
		console.log('onReady');
	},
	onShow() {
		console.log('onShow');
		// 只有在数据为空时才重新加载
		if (!this.labelData.name) {
			this.debouncedLoadData();
		}
	},
	mounted() {
		console.log('mounted');
		// 组件挂载完成后检查是否需要加载数据
		if (!this.labelData.name && this.dictType && this.value) {
			this.debouncedLoadData();
		}
	},
	created() {
		console.log(this.value, this.dictType, 'created');
		// 监听自定义事件，重新加载数据
		uni.$on('dictLabelReload', this.handleReload);

		// 定期清理过期缓存
		this.cleanupTimer = setInterval(() => {
			this.cleanupExpiredCache();
		}, 10 * 60 * 1000); // 每10分钟清理一次
	},
	beforeDestroy() {
		// 清理定时器
		if (this.loadDataTimer) {
			clearTimeout(this.loadDataTimer);
		}
		if (this.cleanupTimer) {
			clearInterval(this.cleanupTimer);
		}
		// 移除事件监听，避免内存泄漏
		uni.$off('dictLabelReload', this.handleReload);
	},
	methods: {
		// 防抖加载数据
		debouncedLoadData() {
			// 清除之前的定时器
			if (this.loadDataTimer) {
				clearTimeout(this.loadDataTimer);
			}

			// 设置新的定时器
			this.loadDataTimer = setTimeout(() => {
				this.loadData();
			}, 50);
		},

		// 处理重新加载事件
		handleReload() {
			console.log('handleReload triggered');
			// 清空当前数据，强制重新加载
			this.labelData = {};
			this.debouncedLoadData();
		},

		async loadData() {
			// 检查必要参数
			if (!this.dictType || this.dictType === '') {
				console.log('dictType is empty, skip loading');
				return;
			}

			// 防止重复请求
			if (this.isLoading) {
				console.log('Already loading, skip this request');
				return;
			}

			console.log('loadData called with:', this.value, this.dictType);
			this.isLoading = true;

			try {
				// 使用字典管理器获取数据，但需要传入API实例
				const result = await this.getDictItemWithApi();
				this.setLabelData(result);
			} catch (error) {
				console.error('dictLabel loadData error:', error);
				// 出错时显示原始值
				const errorData = {
					cssClass:'',
					cssStyle:'',
					name:this.value
				};
				this.setLabelData(errorData);
			} finally {
				this.isLoading = false;
			}
		},

		// 通过API获取字典项数据
		async getDictItemWithApi() {
			// 简化版的字典管理逻辑，直接在组件内实现
			const cacheKey = `${this.dictType}_${this.value}`;

			// 检查组件级缓存
			if (this.$options.dictCache && this.$options.dictCache[cacheKey]) {
				const cached = this.$options.dictCache[cacheKey];
				// 检查缓存是否过期（5分钟）
				if (Date.now() - cached.timestamp < 5 * 60 * 1000) {
					console.log('Using component cached data for:', cacheKey);
					return cached.data;
				}
			}

			// 初始化缓存对象
			if (!this.$options.dictCache) {
				this.$options.dictCache = {};
			}

			// 增加请求计数（用于调试）
			requestCounter++;
			console.log(`🔥 dictLabel API request #${requestCounter} for dictType: ${this.dictType}, value: ${this.value}`);

			const res = await this.$u.api.dictData({dictType: this.dictType});

			if (typeof res === 'object' && res.result === 'login'){
				throw new Error('Login required');
			}

			const arr = res.filter(item => item.value == this.value);
			console.log(arr,'arr===');

			let resultData;
			if(!arr.length){
				resultData = {
					cssClass:'',
					cssStyle:'',
					name:this.value
				}
			}else{
				resultData = {...arr[0]};

				if(resultData.cssClass){
					resultData.cssClass = resultData.cssClass.slice(4, resultData.cssClass.length);
				}
				// 判断resultData.cssStyle 是否存在
				if(resultData.cssStyle){
					resultData.cssStyle = resultData.cssStyle.slice(6, resultData.cssStyle.length)
					if(resultData.cssStyle[resultData.cssStyle.length-1] == ';'){
						let str = resultData.cssStyle
						resultData.cssStyle = str.slice(0, str.length - 1);
					}
				}
			}

			// 缓存结果
			this.$options.dictCache[cacheKey] = {
				data: resultData,
				timestamp: Date.now()
			};

			return resultData;
		},

		// 设置标签数据
		setLabelData(data) {
			// 使用 Vue.set 确保响应式更新
			this.$set(this, 'labelData', data);
			// 确保视图更新
			this.$forceUpdate();
		},

		// 清理过期缓存
		cleanupExpiredCache() {
			if (!this.$options.dictCache) return;

			const now = Date.now();
			const expireTime = 5 * 60 * 1000; // 5分钟

			Object.keys(this.$options.dictCache).forEach(key => {
				const cached = this.$options.dictCache[key];
				if (now - cached.timestamp > expireTime) {
					delete this.$options.dictCache[key];
					console.log('Cleaned up expired cache:', key);
				}
			});
		}
	}
}
</script>
<style lang="scss" scoped>
	
</style>
